<?php

namespace SC\Venus\Support\Traits;

trait Taggable
{
    public function getTagNamesAttribute()
    {
        return $this->tags->pluck('name');
    }

    public function setTagNames($newNames)
    {
        $thisTags = $this->tags;
        $thisTagNames = $thisTags->pluck('name')->all();

        //delete
        foreach($thisTags as $thisTag) {
            if (!\in_array($thisTag->name, $newNames)) {
                $this->tags()->detach($thisTag->id);
            }
        }

        //insert
        foreach($newNames as $newName) {
            if (!\in_array($newName, $thisTagNames)) {
                $newTag = \App\Tag::firstOrCreate(['name' => $newName]);
                $this->tags()->attach($newTag);
            }
        }
    }
}
